package com.recipedb.sprint.controller;

import com.recipedb.sprint.entity.BudgetCount;
import com.recipedb.sprint.entity.UseCount;

import com.recipedb.sprint.service.StatsService;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/api/stats")
public class StatsController {

    private final StatsService statsService;

    public StatsController(StatsService statsService) {
        this.statsService = statsService;
    }

    /**
     * 全量重新统计：品牌 + 关键词
     */
    @PostMapping("/processAll")
    public String processAll() {
        statsService.processAllSessions();
        return "全量统计完成";
    }

    /**
     * 热门关键词（前20）
     */
    @GetMapping("/topKeywords")
    public Map<String, Object> getTopKeywords() {
        List<Map<String, Object>> keywords = statsService.getTopKeywords(20);
        Map<String, Object> result = new HashMap<>();
        result.put("topics", keywords);
        return result;
    }

    /**
     * 热门品牌（前20）
     */
    @GetMapping("/topBrands")
    public Map<String, Object> getTopBrands() {
        List<Map<String, Object>> brands = statsService.getTopBrands(20);
        Map<String, Object> result = new HashMap<>();
        result.put("brands", brands);
        return result;
    }

    /**
     * 预算分布统计（budget_count）
     */
    @GetMapping("/budget")
    public Map<String, Object> getBudgetDistribution() {
        List<BudgetCount> budgets = statsService.getBudgetCounts();
        List<Map<String, Object>> formatted = new ArrayList<>();
        for (BudgetCount b : budgets) {
            Map<String, Object> m = new HashMap<>();
            m.put("name", b.getBudget());
            m.put("value", b.getTotalCount());
            formatted.add(m);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("budgets", formatted);
        return result;
    }

    /**
     * 月度会话统计（use_count）
     */
    @GetMapping("/monthly")
    public Map<String, Object> getMonthlySessions() {
        List<UseCount> months = statsService.getMonthlyCounts();
        List<Map<String, Object>> formatted = new ArrayList<>();
        for (UseCount mth : months) {
            Map<String, Object> m = new HashMap<>();
            m.put("name", mth.getMonth());
            m.put("value", mth.getTotalCount());
            formatted.add(m);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("months", formatted);
        return result;
    }
}